package org.jeecg.modules.wlhy.hyvehicle.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.enums.ExamineStatusEnum;
import org.jeecg.common.constant.enums.ReportPlatformEnum;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.ImageCompressUtil;
import org.jeecg.modules.third.daikai.daoda.DaodaService;
import org.jeecg.modules.third.daikai.daoda.dto.AddUserVehicleDTO;
import org.jeecg.modules.third.jg.report.freight.information.constant.enums.ReportDocTypeEnum;
import org.jeecg.modules.third.jg.report.freight.information.dto.VehicleDTO;
import org.jeecg.modules.third.jg.report.freight.information.service.SdReportPlatformService;
import org.jeecg.modules.third.jg.report.freight.information.service.SxReportPlatformService;
import org.jeecg.modules.third.jg.report.freight.information.util.WebUtils;
import org.jeecg.modules.third.oapi.alct56.constant.enums.ImageCategory;
import org.jeecg.modules.third.oapi.alct56.constant.enums.ImageType;
import org.jeecg.modules.third.oapi.alct56.dto.AlctApiBaseResDTO;
import org.jeecg.modules.third.oapi.alct56.service.OapiAlct56Service;
import org.jeecg.modules.third.openapi.OpenApiService;
import org.jeecg.modules.third.openapi.ZJHYOpenApiService;
import org.jeecg.modules.third.openapi.ZWLWaybillRouteService;
import org.jeecg.modules.third.openapi.dto.VehicleLicenseVO;
import org.jeecg.modules.third.tosapi.constant.enums.EnergyTypeEnum;
import org.jeecg.modules.third.tosapi.constant.enums.PlateColorEnum;
import org.jeecg.modules.third.tosapi.dto.TosApiBaseResDTO;
import org.jeecg.modules.third.tosapi.service.TosApiService;
import org.jeecg.modules.wlhy.captain.entity.HyCaptain;
import org.jeecg.modules.wlhy.captain.entity.HyCaptainVehicle;
import org.jeecg.modules.wlhy.captain.mapper.HyCaptainMapper;
import org.jeecg.modules.wlhy.captain.service.IHyCaptainService;
import org.jeecg.modules.wlhy.captain.service.IHyCaptainVehicleService;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.hydaodauser.entity.HyDaodaUser;
import org.jeecg.modules.wlhy.hydaodauser.service.IHyDaodaUserService;
import org.jeecg.modules.wlhy.hydaodavehicle.entity.HyDaodaVehicle;
import org.jeecg.modules.wlhy.hydaodavehicle.service.IHyDaodaVehicleService;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hydrivercustomer.service.IHyDriverCustomerService;
import org.jeecg.modules.wlhy.hyvehicle.entity.*;
import org.jeecg.modules.wlhy.hyvehicle.mapper.HyVehicleMapper;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyDriverVehicleService;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.setting.entity.HySetting;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 车辆管理
 * @Author: duanlikao
 * @Date:   2020-12-05
 * @Version: V1.0
 */
@Service
@Slf4j
public class HyVehicleServiceImpl extends ServiceImpl<HyVehicleMapper, HyVehicle> implements IHyVehicleService {

    private static final Logger LOGGER = LoggerFactory.getLogger(HyVehicleServiceImpl.class);


    @Resource
    private  HyVehicleMapper hyVehicleMapper;

    @Autowired
    private IHyDriverVehicleService hyDriverVehicleService;

    @Autowired
    private OpenApiService openApiService;

    @Autowired
    private ZJHYOpenApiService zjhyOpenApiService;

    @Resource
    private IHyDriverService driverService;

    @Autowired
    private SxReportPlatformService sxReportPlatformService;

    @Autowired
    private DaodaService daodaService;
    @Autowired
    private IHyDaodaVehicleService hyDaodaVehicleService;

    @Autowired
    private IHyDaodaUserService hyDaodaUserService;

    @Autowired
    private OapiAlct56Service oapiAlct56Service;

    @Autowired
    private TosApiService tosApiService;

    @Autowired
    private SdReportPlatformService sdReportPlatformService;

    @Resource
    private IHySettingService settingService;


    @Autowired
    private IHyDriverCustomerService hyDriverCustomerService;

    @Autowired
    private UserUtil userUtil;

    @Autowired
    private ZWLWaybillRouteService zwlWaybillRouteService;

    @Autowired
    private HyCaptainMapper captainMapper;

    @Autowired
    private IHyCaptainService captainService;
    @Autowired
    private IHyCaptainVehicleService hyCaptainVehicleService;

    /**
     *
     * @param hyVehicle
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result <?>  saveHyVehicle(HyVehicle hyVehicle ){

        if (StringUtils.isEmpty(hyVehicle.getDriverId()) ) {
            throw new JeecgBootException("车辆未绑定司机,请绑定司机");
        }
        HySetting setting = settingService.getByTag("vehicleImg_upload");
        if (setting.getData().equals("1")&&hyVehicle.getVehicleImg()==null||setting.getData().equals("1")&&hyVehicle.getVehicleImg().equals("")){
            return Result.error("人车合照不能为空");
        }
        HySetting setting1 = settingService.getByTag("vehicle_emission_settings");
        if (setting1.getData().equals("1")&&hyVehicle.getEnvironmentalCertificate()==null||setting1.getData().equals("1")&&hyVehicle.getEnvironmentalCertificate().equals("")){
            return Result.error("环保证书不能为空");
        }
        Result<JSONObject> result = new Result<JSONObject>();
        HyVehicle queryHyVehicle =  getHyVehicleByVehicleNumber(hyVehicle.getVehicleNumber());
        boolean  resultSave = false;
        //车辆不为空 并且车辆所属司机为本人时 更新
        //&& StringUtils.equals(hyVehicle.getDriverId(),queryHyVehicle.getDriverId())
        if( queryHyVehicle != null ){
            //当前司机的车辆信息存在并已通过审核 不允许编辑
//            if(!queryHyVehicle.getExamineStatus().equals(ExamineStatusEnum.EXAMINE_STATUS_APPROVED.getCode())){
                //doCheck(hyVehicle);
//                hyVehicle.setExamineStatus(ExamineStatusEnum.EXAMINE_STATUS_APPROVED.getCode());
                hyVehicle.setId(queryHyVehicle.getId());
                resultSave = this.updateById(hyVehicle);
//            }

        }
        //车辆信息为空添加车辆信息
        if(queryHyVehicle == null){
            //doCheck(hyVehicle);
//            hyVehicle.setExamineStatus(ExamineStatusEnum.EXAMINE_STATUS_APPROVED.getCode());
            resultSave =  save(hyVehicle);
        }

        String vehicleId = queryHyVehicle != null   ? queryHyVehicle.getId() : hyVehicle.getId() ;
        resultSave =  this.binding(hyVehicle.getDriverId(),  vehicleId) ;

        result.setSuccess(false);
        result.setCode(CommonConstant.REGISTER_FAILED);
        result.setMessage("车辆信息保存失败,请重新提交信息！");
        result.setTimestamp((new Date()).getTime());
        if(resultSave){
            hyDriverCustomerService.addVehicleCustomer(hyVehicle.getId(),userUtil.getCustomerById());
            if (userUtil.isCaptain()){
                HyCaptainVehicle captainVehicle = new HyCaptainVehicle();
                HyCaptain captain = captainService.getInfoByUserId(userUtil.getLoginUser().getId());
                captainVehicle.setCaptainId(captain.getId());
                captainVehicle.setVehicleId(hyVehicle.getId());
                captainVehicle.setUserId(userUtil.getLoginUser().getId());
                hyCaptainVehicleService.save(captainVehicle);
                HyVehicle hyVehicle1 = new HyVehicle();
                hyVehicle1.setId(captainVehicle.getVehicleId());
                hyVehicle1.setCarrierId(captainVehicle.getCaptainId());
                hyVehicle1.setUpdateBy(userUtil.getLoginUser().getUsername());
                hyVehicle1.setUpdateTime(new Date());
                hyVehicleMapper.updateById(hyVehicle1);
            }
            if (StringUtils.isNotEmpty(hyVehicle.getCarrierId())){
                HyCaptainVehicle captainVehicle = new HyCaptainVehicle();
                HyCaptain captain = captainService.getInfoByUserId(hyVehicle.getCarrierId());
                captainVehicle.setCaptainId(captain.getId());
                captainVehicle.setVehicleId(hyVehicle.getId());
                captainVehicle.setUserId(captain.getUserId());
                hyCaptainVehicleService.save(captainVehicle);
            }

            result.setSuccess(true);
            result.setCode(CommonConstant.SC_OK_200);
            result.setMessage("车辆信息保存成功!");
            result.setResult(
                    JSONObject.parseObject(JSONObject.toJSONString(hyVehicle) )
            );
        }

        return result;

    }



    @Override
    public HyVehicle getHyVehicleByVehicleNumber(String vehicleNumber){
        return hyVehicleMapper.getHyVehicleByVehicleNumber( vehicleNumber);
    }

    @Override
    public HyVehicle getHyVehicleByVehicleNumberAndDriverId(String vehicleNumber , String driverId){
        return hyVehicleMapper.getHyVehicleByVehicleNumberAndDriverId( vehicleNumber,driverId);
    }

    @Override
    public Result<?> getHyVehicleTypeById(Integer pid){

        Result<JSONObject> result = new Result<JSONObject>();
        List<HyVehicleType> hyVehicleTypes = hyVehicleMapper.getHyVehicleTypeById(pid + "");
        if(CollectionUtils.isNotEmpty(hyVehicleTypes)){
            return Result.OK(hyVehicleTypes);
        }
        result.setSuccess(true);
        result.setCode(CommonConstant.SC_OK_200);
        return result;
    }

    @Override
    public List<HyVehicleType> getHyVehicleByPid(String pid) {
        List<HyVehicleType> hyVehicleTypes = hyVehicleMapper.getHyVehicleTypeById(pid);
        return hyVehicleTypes;
    }

    /**
     * 验证行驶证证真实性
     * @param hyVehicle
     */
    private void doCheck(HyVehicle hyVehicle) {
        HyDriver driver = driverService.getById(hyVehicle.getDriverId());
        String res  = checkVehicle(hyVehicle.getVehicleNumber(), driver.getIdcard(),driver.getDriverName());
        hyVehicle.setCarrierId(driver.getIdcard());
        hyVehicle.setExamineStatus(ExamineStatusEnum.EXAMINE_STATUS_TOREVIEWED.getCode());
        if(StringUtils.isNotEmpty(res)){
            JSONObject res_obj = JSONObject.parseObject(res);
            String errorCode =  res_obj.getString("error_code");
            String reason = res_obj.getString("reason");
            if(!"0".equals(errorCode)){
                throw new JeecgBootException(reason);
            }
            JSONObject results_obj = res_obj.getJSONObject("result");
            if(results_obj == null){
                throw new JeecgBootException("参数错误");
            }
            String msg = results_obj.getString("msg");
            Integer code = results_obj.getInteger("code");
            String errMsg ="";
            switch (code){
                case 0:
                    errMsg ="身份证未命中";
                    break;
                case 2:
                    errMsg ="姓名不一致";
                    break;
                case 3:
                    errMsg ="车牌号不一致";
                    break;
            }
            if( code ==1 && "一致".equals(msg)){
                hyVehicle.setExamineStatus(ExamineStatusEnum.EXAMINE_STATUS_APPROVED.getCode());
            }else{
//                        //添加告警信息
//                        LoginUser loginUser = UserUtil.getLoginUser();
//                        HyWarningMessage hyWarningMessage = new HyWarningMessage();
//                        hyWarningMessage.setObjectId(hyVehicle.getId());
//                        hyWarningMessage.setUserId(loginUser.getId());
//                        hyWarningMessage.setMessageType(MessageTypeEnum.MESSAGE_TYPE_UNKNOWN.getCode());
//                        hyWarningMessage.setMessageContent(
//                                "车辆: "+ hyVehicle.getVehicleNumber()+" "+errMsg
//                        );
//                        hyWarningMessage.setCreateBy(loginUser.getUsername());
//                        hyWarningMessage.setCreateTime(new Date());
//                        hyWarningMessageService.saveWarningMessage(hyWarningMessage);

                throw new JeecgBootException(errMsg);
            }
        }
    }

    /**
     * 聚合数据--行驶证证信息查询姓名
     * @param carNo
     * @param IDCardNo
     * @param name
     * @return
     */
    private  String checkVehicle(String carNo ,String IDCardNo ,String name){
        if(StringUtils.isEmpty(IDCardNo)||StringUtils.isEmpty(name) ||StringUtils.isEmpty(carNo)  ){
            return null;
        }
        Map <String, String> params = new HashMap <>();
        params.put("key","33d370a7e20e53e8b0ae5808f802203f");
        params.put("carNo",carNo);
        params.put("IDCardNo",IDCardNo);
        params.put("name",name);
        String url = "http://v.juhe.cn/xszcheck/query";

        String  sendResult = null;
        try {
            sendResult = WebUtils.doPostBuildQuery(url, params, WebUtils.DEFAULT_CHARSET ,null);
            if(StringUtils.isNotEmpty(sendResult)) {
                return sendResult;
            }
        }catch(IOException e) {
            LOGGER.info("HyVehicleServiceImpl checkVehicle  IOException:{}" ,  e.getMessage());
        }
        LOGGER.info("HyVehicleServiceImpl checkVehicle  url:{} | jsonObject:{}"
                ,url, params.toString());
        return null;
    }

//    public static void main(String[] args) {
//        HyVehicleServiceImpl vehicleService= new HyVehicleServiceImpl();
//        String carNo  ="冀EN1269";
//        String IDCardNo  ="130555047002";
//        String name ="邢台荣联货物运输有限公司";
//       String abc =  vehicleService.checkVehicle( carNo , IDCardNo , name);
//       System.out.println(abc);
//    }

    @Override
    public List <HyVehicle> getVehicleByDriverId(String driverId){
        return hyVehicleMapper.getVehicleByDriverId( driverId);
    }


    @Override
    public HyVehicle getVehicletInfo(String id){
        return getById(id);
    }



    /**
     * 推送挂车信息
     * @param hyVehicle
     * @return
     * @throws Exception
     */
    private  String sendTrailerVehicle(HyVehicle hyVehicle, ReportPlatformEnum reportPlatformEnum) throws Exception {
        String jsonString =  StringUtils.EMPTY;

        VehicleDTO vehicleDTO = vehicleDTOTODriverDTO2(hyVehicle);
        if(vehicleDTO != null){
            jsonString =   JSONObject.toJSONString(vehicleDTO);
        }
        String reporDocType = ReportDocTypeEnum.REPORT_DOC_TYPE_WLHY_CL.getCode();
        ReportDocTypeEnum reportDocTypeEnum = ReportDocTypeEnum.getReportDocTypeEnumByVal(reporDocType);
        if(Objects.equals(reportPlatformEnum.getCode(), ReportPlatformEnum.REPORT_PLATFORM_SX.getCode())){
            return   sxReportPlatformService.sendReport(reportDocTypeEnum,jsonString);
        }

        if(Objects.equals(reportPlatformEnum.getCode(), ReportPlatformEnum.REPORT_PLATFORM_SD.getCode())){
            return   sdReportPlatformService.sendReport(reportDocTypeEnum,jsonString);
        }




        return jsonString;

    }
    private static VehicleDTO vehicleDTOTODriverDTO2(HyVehicle hyVehicle ) {
        if (hyVehicle == null) {
            return null;
        }
        VehicleDTO vehicleDTO = new VehicleDTO();
        vehicleDTO.setVehicleNumber(hyVehicle.getTrailerVehiclePlateNumber());
        vehicleDTO.setVehiclePlateColorCode(hyVehicle.getVehiclePlateColorCode());
        vehicleDTO.setVehicleType("B11");
        vehicleDTO.setOwner(hyVehicle.getOwner());
        vehicleDTO.setUseCharacter(hyVehicle.getUseCharacter());
        vehicleDTO.setVin(hyVehicle.getVin());
        vehicleDTO.setIssuingOrganizations(hyVehicle.getIssuingOrganizations());
        vehicleDTO.setRegisterDate(DateUtils.dateToStringNoBar(hyVehicle.getRegisterDate()));
        vehicleDTO.setIssueDate(DateUtils.dateToStringNoBar(hyVehicle.getIssueDate()));
        vehicleDTO.setVehicleEnergyType(hyVehicle.getVehicleEnergyType());
        vehicleDTO.setVehicleTonnage(
                hyVehicle.getVehicleTonnage() != null ?  hyVehicle.getVehicleTonnage()
                        .setScale(2, BigDecimal.ROUND_DOWN).toString() :"40.00"
        );
        vehicleDTO.setGrossMass(
                hyVehicle.getGrossMass() != null ?  hyVehicle.getGrossMass()
                        .setScale(2,BigDecimal.ROUND_DOWN).toString() : "48.00"
        );
        vehicleDTO.setRoadTransportCertificateNumber(
                hyVehicle.getRoadTransportNumber()
        );

        return vehicleDTO;
    }
    @Override
    public HyVehicleType getHyVehicleType(String  vehicleType) {
        return hyVehicleMapper.getHyVehicleTypeByText(vehicleType);
    }

    /**
     * 车辆行驶证信息查询
     * @param hyVehicle
     */
    @Override
    public String vQueryLicenseV2(HyVehicle hyVehicle) {
        if (hyVehicle == null) {
            throw new JeecgBootException("车辆信息为空！");
        }
        //车辆行驶证信息查询
        String res = openApiService.vQueryLicenseV2(hyVehicle.getVehicleNumber(),
                hyVehicle.getVehiclePlateColorCode());
        if(StringUtils.isNotEmpty(res)){
            JSONObject jsonObject = JSONObject.parseObject(res);
            String strResult = jsonObject.get("result") != null ? jsonObject.get("result").toString() :StringUtils.EMPTY ;
            if(jsonObject.get("status").equals(1001) && StringUtils.isNotEmpty(strResult)){
                VehicleLicenseVO result = JSON.parseObject(strResult, VehicleLicenseVO.class);
                String strDrvLicVdy = result.getDrvLicVdy();
                if(StringUtils.isNotEmpty(strDrvLicVdy)){
                    long drvLicVdyTime = Integer.valueOf(strDrvLicVdy ) *1000;
                    Date drvLicVdyDate = DateUtils.getDate(drvLicVdyTime);
                    if(drvLicVdyDate.before(new Date()) ){
//                        //添加告警信息
//                        LoginUser loginUser = UserUtil.getLoginUser();
//
//                        HyWarningMessage hyWarningMessage = new HyWarningMessage();
//                        hyWarningMessage.setObjectId(hyVehicle.getId());
//                        hyWarningMessage.setUserId(loginUser.getId());
//                        hyWarningMessage.setMessageType(MessageTypeEnum.MESSAGE_TYPE_XSZDQ.getCode());
//                        hyWarningMessage.setMessageContent(
//                                "车辆: "+ hyVehicle.getVehicleNumber()+" 行驶证已过期！"
//                        );
//                        hyWarningMessage.setCreateBy(loginUser.getUsername());
//                        hyWarningMessage.setCreateTime(new Date());
//                        hyWarningMessageService.saveWarningMessage(hyWarningMessage);

//                        hyVehicle.setUploadStatus("2");
//                        hyVehicle.setUploadDate(new Date());
//                        hyVehicle.setReportFailureReason("你的行驶证有效期已经到期！");
//                        updateById(hyVehicle);
                        throw new JeecgBootException("你的行驶证有效期已经到期！");
                    }
                    return res;
                }

            }
        }
        return null;
    }



    /**
     * 车辆道路运输证验证
     * 车辆道路运输证号 中交检查
     * @param hyVehiclDb
     */
    @Override
    public boolean checkRTCNoV2(HyVehicle hyVehiclDb) {
        if (hyVehiclDb == null) {
            throw new JeecgBootException("车辆信息为空！");
        }

        if (StrUtil.isEmpty(hyVehiclDb.getVehicleType())) {
            throw new JeecgBootException("车辆类型不存在，请维护车辆信息");
        }

        if(!hyVehiclDb.getVehicleType().contains("重型")){
            return  true;
        }
        //监管上报司机车辆验证开关 关闭不验证
        String updataDrivervehiclValidate = settingService.getSettingValueByTag("updata_drivervehicl_validate");
        if("0".equals(updataDrivervehiclValidate)){
            return  true;
        }
        String resultString =  openApiService.checkRTCNoV2(hyVehiclDb.getVehicleNumber(),
                hyVehiclDb.getVehiclePlateColorCode(),hyVehiclDb.getRoadTransportNumber(),hyVehiclDb.getVin());
        if(StringUtils.isNotEmpty(resultString)){
            JSONObject jsonObject = JSONObject.parseObject(resultString);
            JSONObject resultJsonObject = jsonObject.getJSONObject("result");
            if(1001 == jsonObject.getIntValue("status") && resultJsonObject  != null ){
                //v2 返回结果
                if( "是".equals(resultJsonObject.getString("certificateExpired")) ) {
                    return true;
                }else{
                    throw new JeecgBootException("车辆道路运输证号已过期！");
                }
                //v3 返回结果
                //10000 成功； 10001 查询无结果；10002 参数有误；10003 请求错误；10004 系统错误
                //if("10000".equals(resultJsonObject.getString("code") ) ) {
                //    if( "有效".equals(resultJsonObject.getString("certificateState")) ){
                //        return  true;
                //    }else{
                //        throw new JeecgBootException("车辆道路运输证号已过期！");
                //    }
                //
                //}else if("10001".equals(resultJsonObject.getString("code") )){
                //    throw new JeecgBootException("车辆道路运输证号查询无结果！");
                //}

            }
        }
        return  false;
    }

    /**
     * 中交兴路OpenApi 数据验证车辆入网验证(车牌号)
     * @param hyVehiclDb
     */
    @Override
    public Result checkVehicleNumber(HyVehicle hyVehiclDb) {
        if (hyVehiclDb == null) {
            throw new JeecgBootException("车辆信息为空！");
        }

        HyConfig systemConfig = HyConfigUtils.getConfig();
        if (systemConfig != null && systemConfig.getXzApiIzUse()) {
            return this.checkVehicleStatus(hyVehiclDb);
        }
        //中物联入网查询
        if (systemConfig!=null&&systemConfig.getZwlIsUse()){
            return zwlWaybillRouteService.checkVehicleStatus(hyVehiclDb);
        }
        String checkResult = this.openApiService.checkVehicleExistV2(hyVehiclDb.getVehicleNumber() + "_" + hyVehiclDb.getVehiclePlateColorCode());
        log.info("车辆入网状态查询,{}, {}", hyVehiclDb.getVehicleNumber() + "_" + hyVehiclDb.getVehiclePlateColorCode(), checkResult);

        if (StrUtil.isEmpty(checkResult)) {
            return Result.error("入网验证过程出现错误");
        }

        JSONObject jsonObject = JSONObject.parseObject(checkResult);
        if (1001 == jsonObject.getIntValue("status")) {
            if (jsonObject.getString("result").equals("no")) {
                return Result.error("验证失败,车辆未入网。");
            } else {
                String timeStamp = jsonObject.getString("result");
                Date millisecondDate= new Date(Long.valueOf(timeStamp));
                return Result.OK(DateUtils.dateTimeToString(millisecondDate));
            }
        }

        return Result.error(jsonObject.getString("result"));
    }

    private Result checkVehicleStatus(HyVehicle hyVehiclDb) {
        String checkResult = this.zjhyOpenApiService.checkVehicleStatus(hyVehiclDb.getVehicleNumber() + "_" + hyVehiclDb.getVehiclePlateColorCode());
        log.info("车辆入网状态查询,{}, {}", hyVehiclDb.getVehicleNumber() + "_" + hyVehiclDb.getVehiclePlateColorCode(), checkResult);

        if (StrUtil.isEmpty(checkResult)) {
            return Result.error("入网验证过程出现错误");
        }

        JSONObject jsonObject = JSONObject.parseObject(checkResult);
        if (0 == jsonObject.getIntValue("code")) {
            if (jsonObject.getString("data").equals("no")) {
                return Result.error("验证失败,车辆未入网。");
            } else {
                String timeStamp = jsonObject.getString("data");
                Date millisecondDate= new Date(Long.valueOf(timeStamp));
                return Result.OK(DateUtils.dateTimeToString(millisecondDate));
            }
        }

        return Result.error(jsonObject.getString("data"));
    }


    /**
     * 中交兴路OpenApi 车主真实性验证接口
     * @param hyVehiclDb
     */
    @Override
    public void checkVehicleOwner(HyVehicle hyVehiclDb) {
        if (hyVehiclDb == null) {
            throw new JeecgBootException("车辆信息为空！");
        }

        HyDriver driver = driverService.getById(hyVehiclDb.getDriverId());
        String resultOwnerString =  openApiService.checkOwnerByVclNo(hyVehiclDb.getVehicleNumber(),
                driver.getDriverName(),driver.getTelephone());
        if(StringUtils.isNotEmpty(resultOwnerString)){
            JSONObject jsonObjectOwne = JSONObject.parseObject(resultOwnerString);
            if(jsonObjectOwne.get("status").equals(1001) && !jsonObjectOwne.get("result").equals("yes") ){
                if(jsonObjectOwne.get("result").equals("name") ){
//                    //添加告警信息
//                    LoginUser loginUser = UserUtil.getLoginUser();
//
//                    HyWarningMessage hyWarningMessage = new HyWarningMessage();
//                    hyWarningMessage.setObjectId(hyVehiclDb.getId());
//                    hyWarningMessage.setUserId(loginUser.getId());
//                    hyWarningMessage.setMessageType(MessageTypeEnum.MESSAGE_TYPE_UNKNOWN.getCode());
//                    hyWarningMessage.setMessageContent(
//                            "车辆: "+ hyVehiclDb.getVehicleNumber()+" 车主姓名不正确！"
//                    );
//                    hyWarningMessage.setCreateBy(loginUser.getUsername());
//                    hyWarningMessage.setCreateTime(new Date());
//                    hyWarningMessageService.saveWarningMessage(hyWarningMessage);

                    throw new JeecgBootException("车主姓名不正确！");
                }
                if(jsonObjectOwne.get("result").equals("phone") ){
//                    //添加告警信息
//                    LoginUser loginUser = UserUtil.getLoginUser();
//
//                    HyWarningMessage hyWarningMessage = new HyWarningMessage();
//                    hyWarningMessage.setObjectId(hyVehiclDb.getId());
//                    hyWarningMessage.setUserId(loginUser.getId());
//                    hyWarningMessage.setMessageType(MessageTypeEnum.MESSAGE_TYPE_UNKNOWN.getCode());
//                    hyWarningMessage.setMessageContent(
//                            "车辆: "+ hyVehiclDb.getVehicleNumber()+" 车主手机号不正确！"
//                    );
//                    hyWarningMessage.setCreateBy(loginUser.getUsername());
//                    hyWarningMessage.setCreateTime(new Date());
//                    hyWarningMessageService.saveWarningMessage(hyWarningMessage);

                    throw new JeecgBootException("车主手机号不正确！");
                }

            }
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean uploadDaoda(HyVehicle hyVehicle) {
        HyVehicle hyVehicleDb = getById(hyVehicle.getId());
        if (hyVehicleDb == null) {
            throw new JeecgBootException("未找到对应数据");
        }
//        if(hyVehicleDb.getDaodaUploadStatus().equals("1")){
//            throw new JeecgBootException("该数据已上报过，请勿重复上报！");
//        }

        LambdaQueryWrapper<HyDaodaUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HyDaodaUser::getDriverId,hyVehicle.getDriverId());
        HyDaodaUser daodaUser = hyDaodaUserService.getOne(queryWrapper);
        if(daodaUser == null){
            throw new JeecgBootException("该司机没上报道达，请先上报该司机！");
        }
        HyDriver hyDriver =  driverService.getById(hyVehicle.getDriverId());

        AddUserVehicleDTO addUserVehicleDTO = new AddUserVehicleDTO();
        addUserVehicleDTO.setUserID(daodaUser.getUserId());
        addUserVehicleDTO.setLicenseCode(hyVehicleDb.getVehicleNumber());
        addUserVehicleDTO.setSVehicleModel(hyVehicleDb.getVehicleType());

        Double vehicleLong =  Double.valueOf(hyVehicleDb.getVehicleLong())/1000;
        addUserVehicleDTO.setSVehicleLength(
                vehicleLong.toString()
        );
        Double vehicleWidth=  Double.valueOf(hyVehicleDb.getVehicleWidth())/1000;
        addUserVehicleDTO.setSVehicleWeight(
                vehicleWidth.toString()
        );
        addUserVehicleDTO.setSportsCode(hyDriver.getIdcard());
        addUserVehicleDTO.setSportsThumb(
                daodaService.uploadFiles(hyVehicleDb.getDrivingLicenseImg())
        );
        addUserVehicleDTO.setTransportCode(hyVehicleDb.getRoadTransportNumber());
        addUserVehicleDTO.setTransportCompany(hyVehicleDb.getOwner());
        addUserVehicleDTO.setTransportThumb(
                daodaService.uploadFiles(hyVehicleDb.getRoadTransportImg())
        );

        LambdaQueryWrapper<HyDaodaVehicle> queryWrapperDaodaVehicle = new LambdaQueryWrapper<>();
        queryWrapperDaodaVehicle.eq(HyDaodaVehicle::getDriverId,hyVehicle.getDriverId());
        queryWrapperDaodaVehicle.eq(HyDaodaVehicle::getVehicleId,hyVehicle.getId());
        HyDaodaVehicle daodaVehicle = hyDaodaVehicleService.getOne(queryWrapperDaodaVehicle);
        String reportResult = StringUtils.EMPTY;
        if(daodaVehicle == null){
             reportResult = daodaService.addUserVehicle(addUserVehicleDTO);
        }else{
             addUserVehicleDTO.setVehicleID(daodaVehicle.getDaodaVehicleId());
             reportResult = daodaService.updateUserVehicle(addUserVehicleDTO);
        }

        if(StringUtils.isNotEmpty(reportResult)){
            JSONObject jsonObject = JSONObject.parseObject(reportResult);
            boolean success = jsonObject.getBoolean("success") != null ? jsonObject.getBoolean("success") : false;
            String resultMsg = jsonObject.getString("ResultMsg") != null  ? jsonObject.getString("ResultMsg") :StringUtils.EMPTY;

            hyVehicleDb.setDaodaUploadStatus(success ? "1" : "2");
            hyVehicleDb.setDaodaUploadTime(new Date());
            hyVehicleDb.setDaodaFailureReason(resultMsg);
            updateById(hyVehicleDb);
            if (!success) {
                throw new JeecgBootException(resultMsg);
            }

            HyDaodaVehicle hyDaodaVehicle = new HyDaodaVehicle();
            hyDaodaVehicle.setDriverId(hyVehicle.getDriverId());
            hyDaodaVehicle.setVehicleId(hyVehicleDb.getId());
            if(daodaVehicle == null) {
                String vehicleID = jsonObject.getString("VehicleID");
                hyDaodaVehicle.setDaodaVehicleId(vehicleID);
                hyDaodaVehicleService.save(hyDaodaVehicle);
            }
            return success ;
        }
        return false;
    }

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;
    //辽宁税务上报车辆信息
    @Override
    public Result<?> lnTaxUploadVehicle(HyVehicle hyVehicle){
        if(hyVehicle.getLnTaxUploadStatus() != null) {
            String[] uploadStatus = hyVehicle.getLnTaxUploadStatus().split("\\|");
            if(uploadStatus[0].equals("1")){
                return Result.error("该车辆信息已上报过，请勿重复上报！");
            }

        }

        org.jeecg.modules.third.oapi.alct56.dto.req.vehicle.VehicleDTO vehicleDTO = new org.jeecg.modules.third.oapi.alct56.dto.req.vehicle.VehicleDTO();
        vehicleDTO.setLicensePlateNo(hyVehicle.getVehicleNumber());//	车辆牌照	字符串	7/8位	是	7/8位
        vehicleDTO.setPlateNoColor(hyVehicle.getVehiclePlateColorCode());
        vehicleDTO.setStandardVehicleType(hyVehicle.getVehicleType());//	车辆类型	字符串	最长20为	否
        vehicleDTO.setVehicleIdentityCode(hyVehicle.getVin());//	车架号	字符	17位	是	17位数字与字母组合
        vehicleDTO.setBrand(hyVehicle.getBrandName());//	汽车品牌	字符	最长20位	否
        vehicleDTO.setEngineNumber("");//	发动机号	字符	最长20位	否
        vehicleDTO.setOwner(hyVehicle.getOwner());//	所有人	字符	最长20位	是
        vehicleDTO.setUsage(hyVehicle.getUseCharacter());//	使用性质	字符	最长20位	是
        vehicleDTO.setLoad(hyVehicle.getVehicleTonnage().intValue() * 1000);//	载重	数字	最长6位	是	单位公斤
        vehicleDTO.setTransportLicenseNo(hyVehicle.getRoadTransportNumber());//	道路运输证号	数字	200位	否
        vehicleDTO.setVehicleRegistrationCertificateNo(hyVehicle.getRegistCertNo());//	机动车登记证书编号	开票必传

        vehicleDTO.setOutlineLength(hyVehicle.getVehicleLong());
        vehicleDTO.setOutlineWidth(hyVehicle.getVehicleWidth());
        vehicleDTO.setOutlineHeight(hyVehicle.getVehicleHeight());

        //格式化日期
        DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
        if (ObjectUtil.isNotEmpty(hyVehicle.getRoadTransportExpiredDate())) {
            vehicleDTO.setTransportLicenseExpireDate(dateFormatter.print(new DateTime(hyVehicle.getRoadTransportExpiredDate())));//	道路运输证有效期	日期		否
        }
        if (ObjectUtil.isNotEmpty(hyVehicle.getRegisterDate())) {
            vehicleDTO.setRegTime(dateFormatter.print(new DateTime(hyVehicle.getRegisterDate())));
        }
        if (ObjectUtil.isNotEmpty(hyVehicle.getIssueDate())) {
            vehicleDTO.setCerTime(dateFormatter.print(new DateTime(hyVehicle.getIssueDate())));
        }

        String url = "";
        if(hyVehicle.getIzAffiliation().equals("1")) {
            url = uploadpath + File.separator + hyVehicle.getAffiliationAgreement();
        }
        vehicleDTO.setAffiliationAgreementUrl(url);//	挂靠协议电子合同	字符	最长200	否
        vehicleDTO.setNfcId("");//	Nfc标签	字符	最长20	否
        //登记车辆
        AlctApiBaseResDTO resDTO = oapiAlct56Service.submitVehicle(vehicleDTO);
        if (resDTO.getMessage().contains("已存在")) {
            return Result.OK("辽宁税务：车辆信息已存在！");
        }

        boolean isSuccess = false;
        String status;
        if(resDTO.getCode().equals("0")) {
            isSuccess = true;
            hyVehicle.setLnTaxUploadStatus("1");
        } else {
            isSuccess = false;
            hyVehicle.setLnTaxUploadStatus("2");
        }

        //如果有挂车，再上报一次挂车和车头的绑定关系
        if (isSuccess && StrUtil.isNotEmpty(hyVehicle.getTrailerVehiclePlateNumber()) && hyVehicle.getTrailerVehiclePlateNumber().contains("挂")) {
            org.jeecg.modules.third.oapi.alct56.dto.req.vehicle.VehicleDTO trailerVehicleDTO = new org.jeecg.modules.third.oapi.alct56.dto.req.vehicle.VehicleDTO();
            trailerVehicleDTO.setLicensePlateNo(hyVehicle.getTrailerVehiclePlateNumber());
            trailerVehicleDTO.setPlateNoColor(hyVehicle.getVehiclePlateColorCode());
            trailerVehicleDTO.setStandardVehicleType("重型普通半挂车");//	车辆类型	字符串	最长20为	否
            trailerVehicleDTO.setVehicleIdentityCode(hyVehicle.getVin());//	车架号	字符	17位	是	17位数字与字母组合
            trailerVehicleDTO.setOwner(hyVehicle.getOwner());
            trailerVehicleDTO.setLoad(hyVehicle.getVehicleTonnage().intValue() * 1000);
            trailerVehicleDTO.setUsage("货运");
            log.info("辽宁税务上传挂车信息 -> {}", JSONUtil.toJsonStr(trailerVehicleDTO));
            this.oapiAlct56Service.submitVehicle(trailerVehicleDTO);

            Map<String, String> dto = new HashMap<>();
            dto.put("header", hyVehicle.getVehicleNumber());
            dto.put("body", hyVehicle.getTrailerVehiclePlateNumber());
            log.info("辽宁税务上传车头与挂车绑定信息 -> {}", JSONUtil.toJsonStr(dto));
            this.oapiAlct56Service.submitVehicleTrailer(dto);
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        hyVehicle.setLnTaxUploadTime(format.format(new Date()));
        this.updateById(hyVehicle);
        return isSuccess ? Result.OK("辽宁税务：车辆信息上报成功！") : Result.error(resDTO.getMessage());
    }

    @Override
    public Result<?> updatelnTaxUploadVehicle(HyVehicle hyVehicle) {
        org.jeecg.modules.third.oapi.alct56.dto.req.vehicle.VehicleDTO vehicleDTO = new org.jeecg.modules.third.oapi.alct56.dto.req.vehicle.VehicleDTO();
        vehicleDTO.setLicensePlateNo(hyVehicle.getVehicleNumber());//	车辆牌照	字符串	7/8位	是	7/8位
        vehicleDTO.setPlateNoColor(hyVehicle.getVehiclePlateColorCode());
        vehicleDTO.setStandardVehicleType(hyVehicle.getVehicleType());//	车辆类型	字符串	最长20为	否
        vehicleDTO.setVehicleIdentityCode(hyVehicle.getVin());//	车架号	字符	17位	是	17位数字与字母组合
        vehicleDTO.setBrand(hyVehicle.getBrandName());//	汽车品牌	字符	最长20位	否
        vehicleDTO.setEngineNumber("");//	发动机号	字符	最长20位	否
        vehicleDTO.setOwner(hyVehicle.getOwner());//	所有人	字符	最长20位	是
        vehicleDTO.setUsage(hyVehicle.getUseCharacter());//	使用性质	字符	最长20位	是
        vehicleDTO.setLoad(hyVehicle.getVehicleTonnage().intValue() * 1000);//	载重	数字	最长6位	是	单位公斤
        vehicleDTO.setTransportLicenseNo(hyVehicle.getRoadTransportNumber());//	道路运输证号	数字	200位	否
        vehicleDTO.setVehicleRegistrationCertificateNo(hyVehicle.getRegistCertNo());//	机动车登记证书编号	开票必传

        vehicleDTO.setOutlineLength(hyVehicle.getVehicleLong());
        vehicleDTO.setOutlineWidth(hyVehicle.getVehicleWidth());
        vehicleDTO.setOutlineHeight(hyVehicle.getVehicleHeight());

        //格式化日期
        DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
        if (ObjectUtil.isNotEmpty(hyVehicle.getRoadTransportExpiredDate())) {
            vehicleDTO.setTransportLicenseExpireDate(dateFormatter.print(new DateTime(hyVehicle.getRoadTransportExpiredDate())));//	道路运输证有效期	日期		否
        }
        if (ObjectUtil.isNotEmpty(hyVehicle.getRegisterDate())) {
            vehicleDTO.setRegTime(dateFormatter.print(new DateTime(hyVehicle.getRegisterDate())));
        }
        if (ObjectUtil.isNotEmpty(hyVehicle.getIssueDate())) {
            vehicleDTO.setCerTime(dateFormatter.print(new DateTime(hyVehicle.getIssueDate())));
        }

        //重新上报车辆与司机绑定关系
        HyDriver hyDriver = driverService.getById(hyVehicle.getDriverId());
        List<String> trucks = new ArrayList<>();
        trucks.add(hyVehicle.getVehicleNumber());
        this.oapiAlct56Service.vehicleBoundToDriver(hyDriver.getIdcard(), trucks);

        //登记车辆
        AlctApiBaseResDTO resDTO = this.oapiAlct56Service.put("/api/v1/openapi/trucks", vehicleDTO);
        if (!"0".equals(resDTO.getCode())) {
            return Result.error(resDTO.getMessage());
        }

        //更新车辆时,更新挂车相关的信息
        if (StrUtil.isNotEmpty(hyVehicle.getTrailerVehiclePlateNumber()) && hyVehicle.getTrailerVehiclePlateNumber().contains("挂")) {
            AlctApiBaseResDTO vStatus = this.oapiAlct56Service.queryVehicle(hyVehicle.getTrailerVehiclePlateNumber());
            if (!"0".equals(vStatus.getCode())) {
                org.jeecg.modules.third.oapi.alct56.dto.req.vehicle.VehicleDTO trailerVehicleDTO = new org.jeecg.modules.third.oapi.alct56.dto.req.vehicle.VehicleDTO();
                trailerVehicleDTO.setLicensePlateNo(hyVehicle.getTrailerVehiclePlateNumber());
                trailerVehicleDTO.setPlateNoColor(hyVehicle.getVehiclePlateColorCode());
                trailerVehicleDTO.setStandardVehicleType("重型普通半挂车");//	车辆类型	字符串	最长20为	否
                trailerVehicleDTO.setVehicleIdentityCode(hyVehicle.getVin());//	车架号	字符	17位	是	17位数字与字母组合
                trailerVehicleDTO.setOwner(hyVehicle.getOwner());
                trailerVehicleDTO.setLoad(hyVehicle.getVehicleTonnage().intValue() * 1000);
                trailerVehicleDTO.setUsage("货运");
                log.info("辽宁税务更新车辆信息，重新上传挂车信息 -> {}", JSONUtil.toJsonStr(trailerVehicleDTO));
                this.oapiAlct56Service.submitVehicle(trailerVehicleDTO);

                Map<String, String> dto = new HashMap<>();
                dto.put("header", hyVehicle.getVehicleNumber());
                dto.put("body", hyVehicle.getTrailerVehiclePlateNumber());
                log.info("辽宁税务更新车辆信息，重新上传车头与挂车绑定信息 -> {}", JSONUtil.toJsonStr(dto));
                this.oapiAlct56Service.submitVehicleTrailer(dto);
            }
        }

        return Result.OK("操作成功");
    }

    //辽宁税务上报车辆与司机绑定关系
    @Override
    public Result<?> lnTaxUploadVehicleDriver(HyVehicle hyVehicle){
        // 上报车辆与司机绑定关系
        HyDriver hyDriver = driverService.getById(hyVehicle.getDriverId());
        List<String> trucks = new ArrayList<>();
        trucks.add(hyVehicle.getVehicleNumber());
        AlctApiBaseResDTO resDTO = oapiAlct56Service.vehicleBoundToDriver(hyDriver.getIdcard(), trucks);

        boolean isSuccess = false;
        String[] uploadStatus = hyVehicle.getLnTaxUploadStatus().split("\\|");
        String[] uploadTime = hyVehicle.getLnTaxUploadTime().split("\\|");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = format.format(new Date());

        String status;
        String time;
        if(resDTO.getCode().equals("0") || resDTO.getMessage().contains("已绑定")) {
            isSuccess = true;
            if(uploadStatus.length == 1) {
                status = hyVehicle.getLnTaxUploadStatus() + "|1";
                time = hyVehicle.getLnTaxUploadTime() + "|" + now;

            }else {
                uploadStatus[1] = "1";
                status = String.join("|", uploadStatus);
                uploadTime[1] = now;
                time = String.join("|", uploadTime);
            }
        }else{
            isSuccess = false;
            if(uploadStatus.length == 1) {
                status = hyVehicle.getLnTaxUploadStatus() + "|2";
                time = hyVehicle.getLnTaxUploadTime() + "|" + now;

            }else {
                uploadStatus[1] = "2";
                status = String.join("|", uploadStatus);
                uploadTime[1] = now;
                time = String.join("|", uploadTime);
            }
        }
        hyVehicle.setLnTaxUploadStatus(status);
        hyVehicle.setLnTaxUploadTime(time);
        this.updateById(hyVehicle);
        return isSuccess ? Result.OK("辽宁税务：车辆与司机绑定关系上报成功！") : Result.error(resDTO.getMessage());
    }
    //辽宁税务上传照片
    private AlctApiBaseResDTO lnTaxUploadImg(String vehicleNumber, Map<String, String> imgMap){
        org.jeecg.modules.third.oapi.alct56.dto.req.image.ImageDTO imageDTO = new org.jeecg.modules.third.oapi.alct56.dto.req.image.ImageDTO();
        //司机大头照单独处理
        if(imgMap.get("imageType").equals(ImageType.FullFace.getValue())){
            imageDTO.setIdentityNo(vehicleNumber);//身份证号
            imageDTO.setImageCategory(ImageCategory.Driver.getValue());//照片种类
        }else{
            imageDTO.setLicensePlateNo(vehicleNumber);//车牌号
            imageDTO.setImageCategory(ImageCategory.Truck.getValue());//照片种类
        }
        imageDTO.setImageType(imgMap.get("imageType"));//照片类型
        String img = imgMap.get("img");
        if (StrUtil.isEmpty(img)) {
            AlctApiBaseResDTO resDTO = new AlctApiBaseResDTO();
            resDTO.setCode("1");
            resDTO.setMessage("照片未找到");
            //throw new JeecgBootException("当前车辆(" + imgMap.get("imgInfo") + ")照片未找到");
            return resDTO;
        }

        //img如果没有后缀，按照异常文件处理
        if ( -1 == img.indexOf(".jp") && -1 == img.indexOf(".png")) {
            AlctApiBaseResDTO resDTO = new AlctApiBaseResDTO();
            resDTO.setCode("1");
            resDTO.setMessage("照片未找到");
            return resDTO;
        }

        imageDTO.setFileExt(img.substring(img.lastIndexOf("."), img.length()));//文件类型
        String base64Str = ImageCompressUtil.compressSrcImageToBase64(img,500);
        if (StrUtil.isEmpty(base64Str)) {
            AlctApiBaseResDTO resDTO = new AlctApiBaseResDTO();
            resDTO.setCode("1");
            resDTO.setMessage("照片未找到");
            return resDTO;
        }
        imageDTO.setFileData(base64Str);//照片base64串
        //上报结果
        return oapiAlct56Service.submitImage(imageDTO);
    }
    //辽宁税务上报车辆所需照片(行驶证主页、道路运输证、【行驶证副页正面、行驶证副页反面、车辆机动车登记证书、挂靠协议】、司机大头照)
    //index：-1上报所有照片 0-6上报对应单独照片
    @Override
    public Result<?> lnTaxUploadVehicleImg(HyVehicle hyVehicle, int index){
        //图片List
        List<Map<String, String>> imgList = new ArrayList<>();
        //行驶证主页
        Map<String, String> xszImgMap = new HashMap<>();
        xszImgMap.put("imageType", ImageType.VehicleLicenseMain.getValue());
        xszImgMap.put("imgInfo", ImageType.VehicleLicenseMain.getMsg());
        xszImgMap.put("img", uploadpath + File.separator + hyVehicle.getDrivingLicenseImg());
        //道路运输证
        Map<String, String> dlyszImgMap = new HashMap<>();
        dlyszImgMap.put("imageType", ImageType.TransportationCert.getValue());
        dlyszImgMap.put("imgInfo", ImageType.TransportationCert.getMsg());
        dlyszImgMap.put("img", uploadpath + File.separator + hyVehicle.getRoadTransportImg());
        //行驶证副页正面
        Map<String, String> xszfyzmImgMap = new HashMap<>();
        xszfyzmImgMap.put("imageType", ImageType.VehicleLicenseFront.getValue());
        xszfyzmImgMap.put("imgInfo", ImageType.VehicleLicenseFront.getMsg());
        xszfyzmImgMap.put("img", uploadpath + File.separator + hyVehicle.getDrivingLicenseImg2());
        //行驶证副页反面 没有此照片 先传了行驶证副页正面
        Map<String, String> xszfyfmImgMap = new HashMap<>();
        xszfyfmImgMap.put("imageType", ImageType.VehicleLicenseBack.getValue());
        xszfyfmImgMap.put("imgInfo", ImageType.VehicleLicenseBack.getMsg());
        xszfyfmImgMap.put("img", uploadpath + File.separator + hyVehicle.getDrivingLicenseImg2());
        //机动车登记证书 没有此照片 先传了行驶证副页正面
        Map<String, String> jdcdjzsImgMap = new HashMap<>();
        jdcdjzsImgMap.put("imageType", ImageType.VehicleRegistration.getValue());
        jdcdjzsImgMap.put("imgInfo", ImageType.VehicleRegistration.getMsg());
        jdcdjzsImgMap.put("img", uploadpath + File.separator + hyVehicle.getDrivingLicenseImg2());
        //挂靠协议
        Map<String, String> gkxyImgMap = new HashMap<>();
        gkxyImgMap.put("imageType", ImageType.AffiliationAgreement.getValue());
        gkxyImgMap.put("imgInfo", ImageType.AffiliationAgreement.getMsg());
        if(hyVehicle.getIzAffiliation().equals("1")) {
            gkxyImgMap.put("img", uploadpath + File.separator + hyVehicle.getAffiliationAgreement());
        }else{
            //没有此照片 先传了行驶证副页正面
            gkxyImgMap.put("img", uploadpath + File.separator + hyVehicle.getDrivingLicenseImg2());
        }
        //司机大头照 //先用车辆司机合照
        Map<String, String> sjdtzImgMap = new HashMap<>();
        sjdtzImgMap.put("imageType", ImageType.FullFace.getValue());
        sjdtzImgMap.put("imgInfo", ImageType.FullFace.getMsg());
        sjdtzImgMap.put("img", uploadpath + File.separator + hyVehicle.getVehicleImg());

        imgList.add(xszImgMap);
        imgList.add(dlyszImgMap);
        imgList.add(xszfyzmImgMap);
        imgList.add(xszfyfmImgMap);
        imgList.add(jdcdjzsImgMap);
        imgList.add(gkxyImgMap);
        imgList.add(sjdtzImgMap);

        log.info("辽宁税务上报车辆信息, {} {} {}", hyVehicle.getVehicleNumber(), index, JSONUtil.toJsonStr(imgList));

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String errorMsg = "";
        if(index == -1){
            String uploadStatus = "";
            String uploadTime = "";

            for (int i = 0; i < imgList.size(); i++) {
                Map<String, String> imgMap = imgList.get(i);
                //上报结果
                AlctApiBaseResDTO resDTO;
                //司机大头照单独处理 最后一个是司机大头照
                if(i == imgList.size() - 1){
                    HyDriver hyDriver = driverService.getById(hyVehicle.getDriverId());
                    resDTO = lnTaxUploadImg(hyDriver.getIdcard(), imgMap);
                }else{
                    resDTO = lnTaxUploadImg(hyVehicle.getVehicleNumber(), imgMap);
                }
                if(resDTO.getCode().equals("0")) {
                    uploadStatus += "|1";//上报成功
                }else{
                    uploadStatus += "|2";//上报失败
                    errorMsg += imgMap.get("imgInfo") + "上报失败：" + resDTO.getMessage() + "！";
                }
                //记录上报时间
                Date now = new Date();
                uploadTime += "|" + format.format(now);
            }
            hyVehicle.setLnTaxUploadStatus(hyVehicle.getLnTaxUploadStatus() + uploadStatus);
            hyVehicle.setLnTaxUploadTime(hyVehicle.getLnTaxUploadTime() + uploadTime);
        }else{
            String[] uploadStatus = hyVehicle.getLnTaxUploadStatus().split("\\|");
            String[] uploadTime = hyVehicle.getLnTaxUploadTime().split("\\|");
            AlctApiBaseResDTO resDTO;
            //司机大头照单独处理 最后一个是司机大头照
            if(index == imgList.size() - 1){
                HyDriver hyDriver = driverService.getById(hyVehicle.getDriverId());
                resDTO = lnTaxUploadImg(hyDriver.getIdcard(), imgList.get(index));
            }else{
                resDTO = lnTaxUploadImg(hyVehicle.getVehicleNumber(), imgList.get(index));
            }
            if(resDTO.getCode().equals("0")) {
                uploadStatus[index + 2] = "1";//上报成功
            }else{
                uploadStatus[index + 2] = "2";//上报失败
                errorMsg = resDTO.getMessage();
            }
            //记录上报时间
            Date now = new Date();
            uploadTime[index + 2] = format.format(now);

            hyVehicle.setLnTaxUploadStatus(String.join("|", uploadStatus));
            hyVehicle.setLnTaxUploadTime(String.join("|", uploadTime));
        }
        this.updateById(hyVehicle);
        return errorMsg.equals("") ? Result.OK("上报成功！") : Result.error(errorMsg);
    }
    //辽宁税务上报车辆所有信息
    @Override
    public Result<?> lnTaxUploadVehicleAll(HyVehicle hyVehicle){
        if(hyVehicle.getLnTaxUploadStatus() != null) {
            String[] uploadStatus = hyVehicle.getLnTaxUploadStatus().split("\\|");
            if(uploadStatus[0].equals("1")){
                Result relationRes = lnTaxUploadVehicleDriver(hyVehicle);
                Result imgRes = lnTaxUploadVehicleImg(hyVehicle, -1);

                String msg = "";
                if(!relationRes.isSuccess()){
                    msg += "车辆司机绑定关系上报失败：" + relationRes.getMessage() + "！";
                }
                if(!imgRes.isSuccess()){
                    msg += imgRes.getMessage();
                }
                return msg.equals("") ? Result.OK("上报成功！") : Result.error(msg);
            }
        }

        Result vehicleRes = lnTaxUploadVehicle(hyVehicle);
        //车辆未上报成功时不去调用其它上报接口
        if(!vehicleRes.isSuccess()){
            return Result.error(vehicleRes.getMessage());
        }
        Result relationRes = lnTaxUploadVehicleDriver(hyVehicle);
        Result imgRes = lnTaxUploadVehicleImg(hyVehicle, -1);

        String msg = "";
        if(!relationRes.isSuccess()){
            msg += "车辆司机绑定关系上报失败：" + relationRes.getMessage() + "！";
        }
        if(!imgRes.isSuccess()){
            msg += imgRes.getMessage();
        }
        return msg.equals("") ? Result.OK("上报成功！") : Result.error(msg);
    }

    //辽宁税务上报车辆与司机解绑关系(解绑状态在第2位)
    @Override
    public Result<?> lnTaxUploadUntieVehicleDriver(HyVehicle hyVehicle){
        if(hyVehicle.getLnTaxUploadStatus() == null || hyVehicle.getLnTaxUploadStatus().length() <= 1){
            return Result.OK("辽宁税务绑定关系未上报，无需调用解绑接口。");
        }


        String[] uploadStatus = hyVehicle.getLnTaxUploadStatus().split("\\|");
        String status = uploadStatus[1];
        //检查是否绑定
        if(status.equals("1")) {
            HyDriver hyDriver = driverService.getById(hyVehicle.getDriverId());
            AlctApiBaseResDTO resDTO = oapiAlct56Service.deleteVehicleDriverBound(hyDriver.getIdcard(), hyVehicle.getVehicleNumber());
            if(resDTO.getCode().equals("0")) {
                //绑定关系设置为未上报
                uploadStatus[1] = "0";
                hyVehicle.setLnTaxUploadStatus(String.join("|", uploadStatus));
                this.updateById(hyVehicle);

                return Result.OK("辽宁税务：车辆与司机解绑成功！");
            }else{
                return Result.error(resDTO.getMessage());
            }
        }
        return Result.OK("辽宁税务绑定关系未上报或上报失败，无需调用解绑接口。");
    }
    @Override
    public boolean izVehicleLnUploadSuccess(HyVehicle hyVehicle){
        if(hyVehicle.getLnTaxUploadStatus() != null) {
            String[] uploadStatus = hyVehicle.getLnTaxUploadStatus().split("\\|");
            if(uploadStatus[0].equals("1")) {
                return true;
            }
        }
        return false;
    }

    //快货运上报车辆
    @Override
    public Result<?> tosUploadVehicle(HyVehicle hyVehicle){
        org.jeecg.modules.third.tosapi.dto.vehicle.VehicleDTO vehicleDTO = new org.jeecg.modules.third.tosapi.dto.vehicle.VehicleDTO();
        vehicleDTO.setPlate_number(hyVehicle.getVehicleNumber());//	车辆牌照号	an..35	是	车牌号校验

        //	车牌颜色代码	an..2	是	限制于代码集，
        //蓝色	1	黄色	2
        String color = hyVehicle.getVehiclePlateColorCode();
        vehicleDTO.setPlate_color(color.equals("1") ? PlateColorEnum.BLUENESS.getCode() : PlateColorEnum.YELLOW.getCode());

        //	车辆类型代码
        HyVehicleType hyVehicleType = getHyVehicleType(hyVehicle.getVehicleType());
        if(hyVehicleType == null ){
            return Result.error("不存在的车辆类型：" + hyVehicle.getVehicleType());
        }
        vehicleDTO.setType(hyVehicleType.getValue());//	车辆类型代码	an..3	是	限制于代码集【文档末尾代码集】

        vehicleDTO.setOwner(hyVehicle.getOwner());//	车辆所有人	an..128	是
        vehicleDTO.setUse_character(hyVehicle.getUseCharacter());//	使用性质	an..20	是
        vehicleDTO.setDriving_licence_frontal_pic(tosApiService.uploadFile(hyVehicle.getDrivingLicenseImg()));//	行驶证正面照图片URL	an.1024	是	文件上传接口返回的地址
        vehicleDTO.setDriving_licence_reverse_pic(tosApiService.uploadFile(hyVehicle.getDrivingLicenseImg2()));//	行驶证反面照图片URL	an..1024	是	文件上传接口返回的地址
//        vehicleDTO.setDriving_licence_valid_to("");//	强制报废期	n13	否	13位毫秒时间戳
        vehicleDTO.setVin(hyVehicle.getVin());//	车辆识别代号	an..32	是
        vehicleDTO.setLicence_issuing(hyVehicle.getIssuingOrganizations());//	发证机关	an..128	是
        vehicleDTO.setRegister_date(hyVehicle.getRegisterDate().getTime() + "");//	注册日期	n13	是
        vehicleDTO.setIssue_date(hyVehicle.getIssueDate().getTime() + "");//	发证日期	n13	是
        /*
            vehicle_energy_type字典值
            汽油  	    A
            柴油	        B
            混合油	    D
            天然气	    E
            液化石油气	F
            其他	        Z
        */
        switch (hyVehicle.getVehicleEnergyType()){
            case "A":
                vehicleDTO.setEnergy_type(EnergyTypeEnum.GASOLINE.getCode());//	车辆能源类型	an..12	是	限制于代码集，
                break;
            case "B":
                vehicleDTO.setEnergy_type(EnergyTypeEnum.DIESELOIL.getCode());//	车辆能源类型	an..12	是	限制于代码集，
                break;
            case "D":
                vehicleDTO.setEnergy_type(EnergyTypeEnum.MIXED_OIL.getCode());//	车辆能源类型	an..12	是	限制于代码集，
                break;
            case "E":
                vehicleDTO.setEnergy_type(EnergyTypeEnum.NATURAL_GAS.getCode());//	车辆能源类型	an..12	是	限制于代码集，
                break;
            case "F":
                vehicleDTO.setEnergy_type(EnergyTypeEnum.LIQUEFIED_PETROLEUM_GAS.getCode());//	车辆能源类型	an..12	是	限制于代码集，
                break;
            case "Z":
                vehicleDTO.setEnergy_type(EnergyTypeEnum.OTHER.getCode());//	车辆能源类型	an..12	是	限制于代码集，
                break;
            default:
                //根据错误信息前台修改车辆的能源类型
                vehicleDTO.setEnergy_type(hyVehicle.getVehicleEnergyType());//	车辆能源类型	an..12	是	限制于代码集，
                break;
        }

        vehicleDTO.setRatified_load_capacity(hyVehicle.getVehicleTonnage().toString());//	核定载质量	n..9,2	是	必填，参考机动车行驶证填写，默认单位：吨，保留两位小数，如整数的话，以.00填充。
        vehicleDTO.setTonnage(hyVehicle.getGrossMass().toString());//	吨位	n..9,2	是	必填，车辆总质量，默认单位：吨，保留两位小数，如整数的话，以.00填充。小数点不计入总长。

        vehicleDTO.setMaster_name(hyVehicle.getRoadTransportName());//	业户名称	an..128	是	车辆道路运输证上的业户名称
        vehicleDTO.setTransport_licence_no(hyVehicle.getRoadTransportNumber());//	道路运输证号	n6..20	是	必填，总质量4.5吨及以下普通货运车辆的，可填“车籍地6位行政区域代码+000000”。Pattern:"^\\d{6,20}$"
        if(hyVehicle.getRoadTransportExpiredDate() == null){
            return Result.error("道路运输证过期时间未填写！");
        }
        vehicleDTO.setTransport_licence_valid_to(hyVehicle.getRoadTransportExpiredDate().getTime() + "");//	道路运输证有效期至	n13	是	13位毫秒时间戳。eg：1577811661000，长期传2099-12-31的13位毫秒时间戳
        vehicleDTO.setTransport_licence_frontal_pic(tosApiService.uploadFile(hyVehicle.getRoadTransportImg()));//	道路运输证正面照图片URL		是	文件上传接口返回的地址
        vehicleDTO.setTransport_licence_reverse_pic(tosApiService.uploadFile(hyVehicle.getRoadTransportImg2()));//	道路运输证反面照图片URL		是	文件上传接口返回的地址
        vehicleDTO.setTransport_business_cert_no(hyVehicle.getBusinessLicense());//	道路运输经营许可证号	n12..20	是	车辆所属业户的道路运输经营许可证编号，没有就填车籍地6位行政区划代码+000000，吨位小于等于4.5吨时，道路运输证号和道路运输经营许可证号不能相同

        //	挂车牌照号	an..35	否	当车辆类型代码首字母=B/G/Q时必填，其它情况下，非必填
        String firstLetter = hyVehicleType.getValue().substring(0,1);
        if(firstLetter.equals("B") || firstLetter.equals("G") || firstLetter.equals("Q")){
            vehicleDTO.setTrailer_plate_number(hyVehicle.getTrailerVehiclePlateNumber());
            //	挂车牌照颜色代码	an..35	否	当车辆类型代码首字母=B/G/Q时必填，其它情况下，非必填
            //蓝色	1	黄色	2
            String trailerColor = hyVehicle.getTrailerVehiclePlateColorCode();
            if(trailerColor == null){
                return Result.error("挂车牌照颜色未填写！");
            }


            vehicleDTO.setTrailer_plate_color(trailerColor.equals("1") ? PlateColorEnum.BLUENESS.getCode() : PlateColorEnum.YELLOW.getCode());
        }
        if(hyVehicle.getExamineDate() != null){
            vehicleDTO.setApproved_time(hyVehicle.getExamineDate().getTime() + "");//	营运车辆信息-通过平台审核日期	n13	否	13位毫秒时间戳。eg：1577811661000 广东地区客户必填，否则不传时上报交通取车辆创建时间
        }else{
            vehicleDTO.setApproved_time(hyVehicle.getCreateTime().getTime() + "");//	营运车辆信息-通过平台审核日期	n13	否	13位毫秒时间戳。eg：1577811661000 广东地区客户必填，否则不传时上报交通取车辆创建时间
        }

        TosApiBaseResDTO resDTO = tosApiService.subjectVehicle(vehicleDTO);

        hyVehicle.setTosUploadStatus(resDTO.isSuccess() ? "1" : "2");
        hyVehicle.setTosUploadTime(new Date());
        this.updateById(hyVehicle);
        return resDTO.isSuccess() ? Result.OK("车辆上报成功！") : Result.error(resDTO.getBiz_message());
    }

    /**
     * 彻底删除车辆信息  慎用
     * @param id
     * @return
     */
    @Override
    public int deleteVehicleById(String id){
        return hyVehicleMapper.deleteVehicleById( id);
    }

    //excal表导入
    @Override
    @Transactional
    public void saveBatchVehice(List<ImportHyVehiceDTO> listVehice){
        List<HyVehicle> hyVehicles  = listVehice.stream().map(
                item -> ImportImportHyVehiceDTOTOHyVehice(item)
        ).collect(Collectors.toList());
        this.saveBatch(hyVehicles);
    }


    /**
     * 司机车辆绑定
     * @param driverId
     * @param vehicleId
     * @return
     */
    @Override
    public boolean binding(String driverId  , String vehicleId){

        if(StringUtils.isBlank(driverId) ||StringUtils.isBlank(vehicleId) ){
            return false;
        }
        boolean resultSave;
        LambdaQueryWrapper <HyDriverVehicle> queryWrapper = new LambdaQueryWrapper <>();
        queryWrapper.eq(HyDriverVehicle::getDriverId,driverId);
        queryWrapper.eq(HyDriverVehicle::getVehicleId,vehicleId);
        HyDriverVehicle hyDriverVehicle =  hyDriverVehicleService.getOne(queryWrapper);
        LoginUser user = UserUtil.getLoginUser();
        if(hyDriverVehicle == null){
            HyDriverVehicle saveHyDriverVehicle = new HyDriverVehicle();
            saveHyDriverVehicle.setDriverId(driverId);
            saveHyDriverVehicle.setVehicleId(vehicleId);
            saveHyDriverVehicle.setCreateBy(user.getUsername());
            saveHyDriverVehicle.setCreateTime(new Date());
            resultSave = hyDriverVehicleService.save(saveHyDriverVehicle);
        }else{
            hyDriverVehicle.setIzUsed(1);
            hyDriverVehicle.setUpdateBy(user.getUsername());
            hyDriverVehicle.setUpdateTime(new Date());
            resultSave = hyDriverVehicleService.updateById(hyDriverVehicle);
        }

        //更新车辆表中的司机id
        if (resultSave) {
            return this.update(new LambdaUpdateWrapper<HyVehicle>()
                    .eq(HyVehicle::getId, vehicleId)
                    .set(HyVehicle::getDriverId, driverId));
        }

        return resultSave;
    }

    @Override
    public Result zybBinding(HyVehicleReq hyVehicleReq) {

        String deviceNumber = hyVehicleReq.getVehicleDevice();
        if (0 < this.count(new LambdaQueryWrapper<HyVehicle>().eq(HyVehicle::getVehicleDevice, deviceNumber))) {
            return Result.error("该设备号已绑定，请勿重复绑定");
        }

        boolean bUpdate = this.update(new LambdaUpdateWrapper<HyVehicle>()
                            .eq(HyVehicle::getVehicleNumber, hyVehicleReq.getVehicleNumber())
                            .set(HyVehicle::getVehicleDevice, hyVehicleReq.getVehicleDevice()));
        log.warn("绑定智运宝设备, {}, {}, {}", bUpdate, hyVehicleReq.getVehicleNumber(), deviceNumber);
        if (!bUpdate) {
            return Result.error("更新异常");
        }

        return Result.OK("绑定成功");
    }

    @Override
    public Result zybUnBinding(HyVehicleReq hyVehicleReq) {

        if (0 == this.count(new LambdaQueryWrapper<HyVehicle>()
                .eq(HyVehicle::getVehicleDevice, hyVehicleReq.getVehicleDevice())
                .eq(HyVehicle::getVehicleNumber, hyVehicleReq.getVehicleNumber()))) {
            return Result.error("设备与车辆绑定关系查找失败");
        }

        boolean bUpdate = this.update(new LambdaUpdateWrapper<HyVehicle>()
                .eq(HyVehicle::getVehicleNumber, hyVehicleReq.getVehicleNumber())
                .set(HyVehicle::getVehicleDevice, null));
        log.warn("解绑智运宝设备, {}, {}, {}", bUpdate, hyVehicleReq.getVehicleNumber(), hyVehicleReq.getVehicleDevice());
        if (!bUpdate) {
            return Result.error("更新异常");
        }

        return Result.OK("解绑成功");
    }

    @Override
    public IPage<HyVehicle> pageList(Page<HyVehicle> page, QueryWrapper<HyVehicle> queryWrapper, String customerId) {
        return page.setRecords(baseMapper.pageList(page, queryWrapper,customerId));
    }

    @Override
    public int getDsvehicleCount(String customerById) {
        return baseMapper.getDsvehicleCount(customerById);
    }

    @Override
    public boolean updateJgUploadStatusById(String id, String status) {
        return this.update(new LambdaUpdateWrapper<HyVehicle>().eq(HyVehicle::getId, id)
                .set(HyVehicle::getUploadDate, new Date())
                .set(HyVehicle::getUploadStatus, status));
    }

    @Override
    public boolean updateSxUploadStatusById(String id, String status) {
        return this.update(new LambdaUpdateWrapper<HyVehicle>().eq(HyVehicle::getId, id)
                .set(HyVehicle::getSxUploadDate, new Date())
                .set(HyVehicle::getSxUploadStatus, status));
    }

    @Override
    public boolean updateAhUploadStatusById(String id, String status) {
        return this.update(new LambdaUpdateWrapper<HyVehicle>().eq(HyVehicle::getId, id)
                .set(HyVehicle::getAhUploadDate, new Date())
                .set(HyVehicle::getAhUploadStatus, status));
    }

    @Override
    public boolean updateHbUploadStatusById(String id, String status) {
        return this.update(new LambdaUpdateWrapper<HyVehicle>().eq(HyVehicle::getId, id)
                .set(HyVehicle::getHbUploadDate, new Date())
                .set(HyVehicle::getHbUploadStatus, status));
    }

    @Override
    public boolean updateYuanquUploadStatusById(String id, String status) {
        return this.update(new LambdaUpdateWrapper<HyVehicle>().eq(HyVehicle::getId, id)
                .set(HyVehicle::getXzUploadDate, new Date())
                .set(HyVehicle::getXzUploadStatus, status));
    }

    @Override
    public boolean updateJxUploadStatusById(String id, String status) {
        return this.update(new LambdaUpdateWrapper<HyVehicle>().eq(HyVehicle::getId, id)
                .set(HyVehicle::getJxUploadDate, new Date())
                .set(HyVehicle::getJxUploadStatus, status));
    }

    @Override
    public boolean updateJsUploadStatusById(String id, String status) {
        return this.update(new LambdaUpdateWrapper<HyVehicle>().eq(HyVehicle::getId, id)
                .set(HyVehicle::getJsUploadDate, new Date())
                .set(HyVehicle::getJsUploadStatus, status));
    }

    @Override
    public boolean updateZjUploadStatusById(String id, String status) {
        return this.update(new LambdaUpdateWrapper<HyVehicle>().eq(HyVehicle::getId, id)
                .set(HyVehicle::getZjUploadDate, new Date())
                .set(HyVehicle::getZjUploadStatus, status));
    }

    @Override
    public boolean updateHubeiUploadStatusById(String id, String status) {
        return this.update(new LambdaUpdateWrapper<HyVehicle>().eq(HyVehicle::getId, id)
                .set(HyVehicle::getHubeiUploadDate, new Date())
                .set(HyVehicle::getHubeiUploadStatus, status));
    }

    private HyVehicle ImportImportHyVehiceDTOTOHyVehice(ImportHyVehiceDTO importHyVehiceDTO) {
        if (importHyVehiceDTO == null) {
            return null;
        }
        HyVehicle hyVehicle = new HyVehicle();
        hyVehicle.setVehicleNumber(importHyVehiceDTO.getVehicleNumber());
        hyVehicle.setVehiclePlateColorCode(importHyVehiceDTO.getVehiclePlateColorCode());
        hyVehicle.setVehicleType(importHyVehiceDTO.getVehicleType());
        hyVehicle.setOwner(importHyVehiceDTO.getOwner());
        hyVehicle.setUseCharacter(importHyVehiceDTO.getUseCharacter());
        hyVehicle.setVin(importHyVehiceDTO.getVin());
        hyVehicle.setIssuingOrganizations(importHyVehiceDTO.getIssuingOrganizations());
        hyVehicle.setRegisterDate(
                DateUtils.getStrToDate(  importHyVehiceDTO.getRegisterDate())
        );
        hyVehicle.setIssueDate(
                DateUtils.getStrToDate(  importHyVehiceDTO.getIssueDate())
        );
        hyVehicle.setVehicleEnergyType(importHyVehiceDTO.getVehicleEnergyType());
        hyVehicle.setVehicleTonnage(importHyVehiceDTO.getVehicleTonnage());
        hyVehicle.setGrossMass(importHyVehiceDTO.getGrossMass());
        hyVehicle.setRoadTransportNumber(importHyVehiceDTO.getRoadTransportCertificateNumber());
        hyVehicle.setExamineStatus(ExamineStatusEnum.EXAMINE_STATUS_TOREVIEWED.getCode());

        //选填

        hyVehicle.setVehicleLong(importHyVehiceDTO.getVehicle_long());
        hyVehicle.setVehicleWidth(importHyVehiceDTO.getVehicle_width());
        hyVehicle.setVehicleHeight(importHyVehiceDTO.getVehicle_height());
        hyVehicle.setDrivingLicenseNum(importHyVehiceDTO.getDriving_license_num());
        if (StrUtil.isNotEmpty(importHyVehiceDTO.getTrailer_vehicle_plate_number())) {
            hyVehicle.setTrailerVehiclePlateNumber(importHyVehiceDTO.getTrailer_vehicle_plate_number());
            //默认黄色
            hyVehicle.setTrailerVehiclePlateColorCode("2");
        }
        hyVehicle.setTrailerVehicleType(importHyVehiceDTO.getTrailerVehicleType());
        hyVehicle.setTrailerVehicleRoadTransportNumber(importHyVehiceDTO.getTrailerVehicleRoadTransportNumber());

        hyVehicle.setRoadTransportName(importHyVehiceDTO.getRoad_transport_name());
        hyVehicle.setRegistCertNo(importHyVehiceDTO.getRegist_cert_no());
        if (StrUtil.isNotEmpty(importHyVehiceDTO.getBrand_name())) {
            hyVehicle.setBrandName(importHyVehiceDTO.getBrand_name());
        } else {
            hyVehicle.setBrandName("--");
        }
        if (StrUtil.isNotEmpty(importHyVehiceDTO.getVehicle_address())) {
            hyVehicle.setVehicleAddress(importHyVehiceDTO.getVehicle_address());
        } else {
            hyVehicle.setVehicleAddress("--");
        }

        hyVehicle.setBusinessLicense(importHyVehiceDTO.getBusiness_license());
        hyVehicle.setRoadTransportExpiredDate(
                DateUtils.getStrToDate(importHyVehiceDTO.getRoad_transport_expired_date())
        );

        //图片URL保存
        if (StrUtil.isNotEmpty(importHyVehiceDTO.getDrivingLicenseImg())) {
            hyVehicle.setDrivingLicenseImg(importHyVehiceDTO.getDrivingLicenseImg());
        }
        //行驶证反面
        if (StrUtil.isNotEmpty(importHyVehiceDTO.getDrivingLicenseImg2())) {
            hyVehicle.setDrivingLicenseImg2(importHyVehiceDTO.getDrivingLicenseImg2());
        }
        //驾驶证主页
        if (StrUtil.isNotEmpty(importHyVehiceDTO.getRoadTransportImg())) {
            hyVehicle.setRoadTransportImg(importHyVehiceDTO.getRoadTransportImg());
        }
        //挂车照片正面
        if (StrUtil.isNotEmpty(importHyVehiceDTO.getTrailerVehiclLicenseImg())) {
            hyVehicle.setTrailerVehiclLicenseImg(importHyVehiceDTO.getTrailerVehiclLicenseImg());
        }
        //挂车照片反面
        if (StrUtil.isNotEmpty(importHyVehiceDTO.getTrailerVehiclLicenseImg2())) {
            hyVehicle.setTrailerVehiclLicenseImg2(importHyVehiceDTO.getTrailerVehiclLicenseImg2());
        }
        //挂车道路运输证照片
        if (StrUtil.isNotEmpty(importHyVehiceDTO.getTrailerVehicleRoadTransportImg())) {
            hyVehicle.setTrailerVehicleRoadTransportImg(importHyVehiceDTO.getTrailerVehicleRoadTransportImg());
        }
        //人车合照
        if (StrUtil.isNotEmpty(importHyVehiceDTO.getVehicleImg())) {
            hyVehicle.setVehicleImg(importHyVehiceDTO.getVehicleImg());
        }
        //车辆入库时间/创建时间
        if (StrUtil.isEmpty(importHyVehiceDTO.getCreateTime())) {
            hyVehicle.setCreateTime(DateUtils.getStrToDate(importHyVehiceDTO.getCreateTime()));
        }

        hyVehicle.setVehicleImportFlag("1");
        return hyVehicle;
    }

//    public static void main(String[] args) {
//        String PlateNumMatch = "^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏黔川滇宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏黔川滇宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$";
//        boolean m1 = "闽E123S0".matches(PlateNumMatch);
//        System.out.println(m1);//true
//        boolean m2 = "闽d12345".matches(PlateNumMatch);
//        System.out.println(m2);//false
//    }

    /**
     * 根据承运商id获取绑定的车辆列表
     * @param hyCaptainId
     * @return
     */
    @Override
    public Result<?> getVehicleListByHyCaptainId(String hyCaptainId) {
        List<String> vehiceleIds =  captainMapper.getHyVehicleIds(hyCaptainId);
        if (vehiceleIds.size() > 0){
            List<HyVehicle> vehicles = baseMapper.selectBatchIds(vehiceleIds);
            return Result.OK(vehicles);
        }
        return Result.OK();
    }

    /**
     * 根据车辆id获取绑定的司机列表
     * @param vehicleId
     * @return
     */
    @Override
    public List<HyDriver> getDriversByVehicleId(String vehicleId) {
        return baseMapper.getDriversByVehicleId(vehicleId);
    }
    @Override
    public IPage<HyVehicle> pageList1(Page<HyVehicle> page, QueryWrapper<HyVehicleDTO> queryWrapper, String customerId) {
        return page.setRecords(baseMapper.pageList1(page, queryWrapper,customerId));
    }


}
